package top.foxhome.web.spiders.document_process.simple;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import top.foxhome.web.spiders.document_process.IDocumentProcess;
import top.foxhome.web.spiders.download.DownloadManager;
import top.foxhome.web.spiders.util.UrlUtil;

import java.io.File;
import java.net.URISyntaxException;

/**
 * 图片下载工具
 */
public class ImgDownloadDocumentProcess implements IDocumentProcess {
    /**
     * 图片文件保存路径
     */
    public static String IMG_DOWN_LOAD_PATH;

    static {
        try {
            // 获取正在运行的 JAR 文件的路径
            String jarPath = ImgDownloadDocumentProcess.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath();
            // 如果是在 Windows 系统下，去掉路径前面的斜杠
            if (System.getProperty("os.name").startsWith("Windows") && jarPath.startsWith("/")) {
                jarPath = jarPath.substring(1);
            }
            // 创建 File 对象
            File jarFile = new File(jarPath);
            // 获取 JAR 文件所在的目录
            IMG_DOWN_LOAD_PATH = jarFile.getParent() + "/img";
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    private DownloadManager mDownloadManager;

    public ImgDownloadDocumentProcess() {
        mDownloadManager = new DownloadManager();
    }

    @Override
    public void onDocument(String host, String url, Document document) {
        System.out.println("-------开始处理" + url + "页面内容-------");
        Element bodyElement = document.body();
        //找寻到页面图片并进行处理
        Elements imgElements = bodyElement.getElementsByTag("img");
        imgElements.forEach(element -> {
            String src = element.attr("src");
            if (UrlUtil.isBase64ImageData(src)) {
                String fileName = UrlUtil.base64ToFileName(src);
                mDownloadManager.downloadBase64Date(src, IMG_DOWN_LOAD_PATH, fileName);
                return;
            }
            src = UrlUtil.buildUrl(src, url, host);
            String fileName = UrlUtil.urlToFileName(src);
            if (fileName == null || fileName.length() == 0) return;
            mDownloadManager.download(src, IMG_DOWN_LOAD_PATH, fileName);
            System.out.println("得到的图片链接为:" + src);
        });
        System.out.println("-------处理" + url + "页面内容结束-------");
    }
}
